<template>
  <!-- 标准检验项目表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="1000px"
    draggable
    @close="closeDialog"
  >
    <el-form
      v-show="!props.isReadonly"
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目规范码" prop="checkItemCode">
            <el-input
              v-model="formData.checkItemCode"
              placeholder="请输入项目规范码"
            />
          </el-form-item>
        </el-col>
        <!--        <el-col :span="8">-->
        <!--          <el-form-item label="操作类型" prop="opeTypeCode">-->
        <!--            <el-select-->
        <!--              style="width: 100%"-->
        <!--              v-model="formData.opeTypeCode"-->
        <!--              placeholder="请选择操作类型"-->
        <!--              :disabled="isBind"-->
        <!--              @change="changeOperateType"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="item in dictionaryStore.filterDictList(-->
        <!--                  'CheckOperateType'-->
        <!--                )"-->
        <!--                :key="item.value"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="8">-->
        <!--          <el-form-item label="事务类型" prop="effectTypeCode">-->
        <!--            <el-select-->
        <!--              style="width: 100%"-->
        <!--              v-model="formData.effectTypeCode"-->
        <!--              placeholder="请选择事务类型"-->
        <!--              :disabled="isBind"-->
        <!--              @change="changeEffectType"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="item in effectTypeCodeList"-->
        <!--                :key="item.value"-->
        <!--                :label="item.label"-->
        <!--                :value="item.value"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="8">
          <el-form-item label="检验项目名称" prop="checkItemName">
            <el-input
              v-model="formData.checkItemName"
              placeholder="请输入检验项目名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验类型" prop="effectCheckTypeId">
            <el-select
              style="width: 100%"
              v-model="formData.effectCheckTypeId"
              placeholder="请选择检验类型"
              :disabled="isBind"
            >
              <el-option
                v-for="item in effectCheckTypeList"
                :key="item.id"
                :label="item.checkTypeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目" prop="projectId">
            <el-select
              style="width: 100%"
              v-model="formData.projectId"
              placeholder="请选择项目"
              clearable
              :disabled="isBind"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工序" prop="processId">
            <el-select
              style="width: 100%"
              v-model="formData.processId"
              placeholder="请选择工序"
              clearable
              :disabled="isBind"
              @change="changeProduct"
            >
              <el-option
                v-for="item in processList"
                :key="item.id"
                :label="item.processName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="检验规则" prop="effectCheckRuleId">
            <el-select
              style="width: 100%"
              v-model="formData.effectCheckRuleId"
              placeholder="请选择检验规则"
              clearable
            >
              <el-option
                v-for="item in checkRuleList"
                :key="item.id"
                :label="item.ruleName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="检验项目描述" prop="checkItemRemark">
            <el-input
              type="textarea"
              v-model="formData.checkItemRemark"
              placeholder="请输入检验项目描述"
              rows="1"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!--        <el-col :span="3" />-->
        <el-col :span="5">
          <el-form-item prop="needMaterialBatch">
            <el-checkbox
              v-model="formData.needMaterialBatch"
              label="是否输入物料批次号"
              :true-label="1"
              :false-label="0"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item prop="needMaterialSerial">
            <el-checkbox
              v-model="formData.needMaterialSerial"
              label="是否输入物料序列号"
              value="1"
              :true-label="1"
              :false-label="0"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item prop="needProcess">
            <el-checkbox
              v-model="formData.needProcess"
              label="是否输入工序"
              value="1"
              :true-label="1"
              :false-label="0"
              size="large"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item prop="needEquip">
            <el-checkbox
              v-model="formData.needEquip"
              label="是否输入设备"
              value="1"
              :true-label="1"
              :false-label="0"
              size="large"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="产品号" prop="productId">
            <el-select
              style="width: 100%"
              v-model="formData.productId"
              placeholder="请选择产品号"
              :disabled="isBind"
              filterable
              :filter-method="productFilter"
              @change="changeProduct"
            >
              <el-option
                v-for="item in productFilteredOptions"
                :key="item.id"
                :label="item.materialName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="标准作业规程" prop="standardId">
            <el-select
              style="width: 100%"
              v-model="formData.standardId"
              placeholder="请选择标准作业规程"
              :disabled="isBind"
              @change="changeStandard"
            >
              <el-option
                v-for="item in standardList"
                :key="item.id"
                :label="item.standardName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否启用" prop="enabled">
            <el-radio-group v-model="formData.enabled" :disabled="isBind">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-descriptions
      v-show="props.isReadonly"
      class="margin-top w-full"
      title=""
      :column="3"
      size="large"
      border
      style="padding-bottom: 30px"
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">项目规范码</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkItemCode || "" }}
        </div>
      </el-descriptions-item>
      <!--      <el-descriptions-item>-->
      <!--        <template #label>-->
      <!--          <div class="cell-item">操作类型</div>-->
      <!--        </template>-->
      <!--        <div style="width: 100%; word-break: break-all">-->
      <!--          {{ useDictionary("CheckOperateType", formData.opeTypeCode) || "" }}-->
      <!--        </div>-->
      <!--      </el-descriptions-item>-->
      <!--      <el-descriptions-item>-->
      <!--        <template #label>-->
      <!--          <div class="cell-item">事务类型</div>-->
      <!--        </template>-->
      <!--        <div style="width: 100%; word-break: break-all">-->
      <!--          {{ getEffectTypeCode(formData) }}-->
      <!--        </div>-->
      <!--      </el-descriptions-item>-->
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">检验项目名称</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkItemName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">检验类型</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkTypeName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">项目</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.projectName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">工序</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.processName || "" }}
        </div>
      </el-descriptions-item>
      <!-- <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否启用</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          <el-tag type="success" v-if="formData.enabled === 1">启用</el-tag>
          <el-tag type="info" v-else>停用</el-tag>
        </div>
      </el-descriptions-item> -->
      <el-descriptions-item :span="3">
        <template #label>
          <div class="cell-item">检验规则</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ checkRuleName(formData.effectCheckRuleId) }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item :span="3">
        <template #label>
          <div class="cell-item">检验项目描述</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.checkItemRemark || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否输入物料批次号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.needMaterialBatch ? "是" : "否" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否输入物料序列号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.needMaterialSerial ? "是" : "否" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否输入工序</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.needProcess ? "是" : "否" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">是否输入设备</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.needEquip ? "是" : "否" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">产品号</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.productName || "" }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">标准作业规程</div>
        </template>
        <div style="width: 100%; word-break: break-all">
          {{ formData.standardName || "" }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="sopItemList"
      highlight-current-row
      border
      max-height="350px"
    >
      <el-table-column
        label="作业项编号"
        prop="sopItemCode"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="作业项名称"
        prop="sopItemName"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="标准值类型"
        prop="standardValue"
        min-width="100"
        show-overflow-tooltip
        align="center"
      >
        <template #default="{ $index, row }">
          {{ useDictionary("standardValue", row.standardValue) }}
        </template>
      </el-table-column>
      <el-table-column
        label="上限值"
        prop="standardMaxValue"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="下限值"
        prop="standardMinValue"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="数据来源"
        prop="effectTypeCode"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="附件内容"
        prop="images"
        min-width="75"
        show-overflow-tooltip
      >
        <template #default="{ $index, row }">
          <div style="display: flex; flex-wrap: wrap">
            <span v-for="(item, index) in row.images" :key="index">
              <img
                :src="`${upPreviewUrl}${item.url}`"
                style="
                  width: 30px;
                  height: 30px;
                  margin-right: 10px;
                  cursor: pointer;
                "
                @click="handlePictureCardPreview(`${upPreviewUrl}${item.url}`)"
                alt=""
              />
            </span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
import { checkCommon } from "@/views/qms/checkHook/checkCommon"; // 引入
import _ from "lodash-es";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSCHECKITEMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
const isBind = ref(false);

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;
const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  sopType: {
    type: String,
    default: "",
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  // effectTypeCode: [
  //   { required: true, message: "请选择事务类型", trigger: ["blur", "change"] },
  // ],
  projectId: [],
  processId: [],
  checkItemName: [
    {
      required: true,
      message: "请输入项目规范名称",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  checkItemCode: [
    {
      required: true,
      message: "请输入项目规范码",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  checkItemRemark: [
    {
      min: 1,
      max: 255,
      message: "长度在 1 到 255 个字符",
      trigger: ["blur", "change"],
    },
  ],
  // opeTypeCode: [
  //   { required: true, message: "请选择操作类型", trigger: ["blur", "change"] },
  // ],
  effectCheckTypeId: [
    { required: true, message: "请选择检验类型", trigger: ["blur", "change"] },
  ],
  standardId: [
    {
      required: true,
      message: "请选择标准作业规程",
      trigger: ["blur", "change"],
    },
  ],
  remarks: [
    {
      min: 1,
      max: 255,
      message: "长度在 1 到 255 个字符",
      trigger: ["blur", "change"],
    },
  ],
  productId: [
    { required: true, message: "请选择产品", trigger: ["blur", "change"] },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  standardId: "",
  standardCode: "",
  standardName: "",
  productId: "",
  effectTypeCode: "",
  effectCheckTypeId: "",
  effectCheckRuleId: "",
  checkTypeName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  processId: "",
  processCode: "",
  processName: "",

  productCode: "",
  productName: "",
  checkItemCode: "",
  checkItemName: "",
  checkItemRemark: "",
  needMaterialBatch: 0,
  needMaterialSerial: 0,
  needProcess: 0,
  needEquip: 0,
  opeTypeCode: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

const { changeOpeType, getEffectTypeCode, effectTypeCodeList } = checkCommon(
  ref(formData)
);
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        standardId,
        standardCode,
        standardName,
        effectTypeCode,
        effectCheckTypeId,
        checkTypeName,
        projectId,
        projectCode,
        projectName,
        processId,
        processCode,
        processName,
        productId,
        productCode,
        productName,
        checkItemCode,
        checkItemName,
        checkItemRemark,
        needMaterialBatch,
        needMaterialSerial,
        needProcess,
        needEquip,
        opeTypeCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        bind,
        effectCheckRuleId,
      } = newVal;
      isBind.value = bind;
      changeOperateType(opeTypeCode);
      // changeEffectType(effectTypeCode, opeTypeCode);
      Object.assign(formData, {
        id,
        version,
        standardId,
        standardCode,
        standardName,
        effectTypeCode,
        effectCheckTypeId,
        checkTypeName,
        projectId,
        projectCode,
        projectName,
        processId,
        processCode,
        processName,
        productId,
        productCode,
        productName,
        checkItemCode,
        checkItemName,
        checkItemRemark,
        needMaterialBatch: needMaterialBatch ?? 0,
        needMaterialSerial: needMaterialSerial ?? 0,
        needProcess: needProcess ?? 0,
        needEquip: needEquip ?? 0,
        opeTypeCode,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
        bind,
        effectCheckRuleId,
      });
      await getProcessList();
      await getStandardList();
      await changeStandard();
      await getCheckRuleList();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.standardId = "";
  formData.standardCode = "";
  formData.standardName = "";
  formData.effectTypeCode = "";
  formData.effectCheckTypeId = "";
  formData.checkTypeName = "";
  formData.projectId = "";
  formData.projectCode = "";
  formData.projectName = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.checkItemCode = "";
  formData.checkItemName = "";
  formData.checkItemRemark = "";
  formData.needMaterialBatch = 0;
  formData.needMaterialSerial = 0;
  formData.needProcess = 0;
  formData.needEquip = 0;
  formData.opeTypeCode = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.effectCheckRuleId = "";
  effectTypeCodeList.value = [];
  // effectCheckTypeList.value = [];
  processList.value = [];
  standardList.value = [];
  sopItemList.value = [];
  isBind.value = false;
}

const loading = ref(false);

/** 标准检验项目保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const project = projectList.value.find(
        (item: any) => item.id == formData.projectId
      );
      formData.projectCode = project?.projectCode;
      formData.projectName = project?.projectName;
      const process = processList.value.find(
        (item: any) => item.id == formData.processId
      );
      formData.processCode = process?.processCode;
      formData.processName = process?.processName;
      const product = productList.value.find(
        (item: any) => item.id == formData.productId
      );
      formData.productCode = product?.materialCode;
      formData.productName = product?.materialName;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmscheckitem/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const changeOperateType = (val) => {
  formData.effectCheckTypeId = "";
  // effectCheckTypeList.value = [];
  changeOpeType(val);
};
const projectList = ref([]);

const getProjectList = async () => {
  const { data } = await request({
    url: "/mdm/mdmprojectinfo/getList",
    method: "post",
    data: {},
  });
  projectList.value = data;
};

const processList = ref([]);

const getProcessList = async () => {
  const { data } = await request({
    url: "/mes/mesprocess/getList",
    method: "post",
    data: {},
  });
  processList.value = data;
};

const productList = ref([]);

const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getList",
    method: "post",
    data: {},
  });
  productList.value = data;
  productFilteredOptions.value = data;
};

const productFilteredOptions = ref<any>([]);

// 使用 debounce 包装过滤方法
const productFilter = _.debounce((query: any) => {
  if (!query) {
    productFilteredOptions.value = [...productList.value];
    return;
  }
  productFilteredOptions.value = productList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

onMounted(() => {
  getProjectList();
  getProcessList();
  getProductList();
  getEffectType();
  getCheckRuleList();
});
const effectCheckTypeList = ref([]);
// const changeEffectType = async (val, opeTypeCode) => {
//   formData.effectCheckTypeId = "";
//   const { data } = await request({
//     url: "/qms/qmschecktype/getList",
//     method: "post",
//     data: {
//       opeTypeCode: opeTypeCode ?? formData.opeTypeCode,
//       effectTypeCode: val,
//     },
//   });
//   effectCheckTypeList.value = data;
// };
const getEffectType = async () => {
  formData.effectCheckTypeId = "";
  const { data } = await request({
    url: "/qms/qmschecktype/getList",
    method: "post",
    data: {},
  });
  effectCheckTypeList.value = data;
};

const standardList = ref([]);
const changeProduct = async () => {
  formData.standardId = "";
  sopItemList.value = [];
  getStandardList();
};

const getStandardList = async () => {
  const { data } = await request({
    url: "/qms/qmssopstandard/getList",
    method: "post",
    data: {
      productId: formData.productId,
      processId: formData.processId,
      sopTypeCode: props.sopType,
    },
  });
  standardList.value = data;
};

const sopItemList = ref([]);
const changeStandard = async () => {
  const { data } = await request({
    url: "/qms/qmssopitem/getList",
    method: "post",
    data: {
      standardId: formData.standardId,
    },
  });
  sopItemList.value = data;
};
const checkRuleList = ref<any>([]);
const getCheckRuleList = async () => {
  const { data } = await request({
    url: "/qms/qmscheckrule/getList",
    method: "post",
    data: {},
  });
  checkRuleList.value = data;
};

const checkRuleName = (id: String) => {
  const checkRule: any = checkRuleList.value.find((item: any) => {
    return item.id == formData.effectCheckRuleId;
  });
  if (checkRule) {
    return checkRule.ruleName;
  }
  return "";
};
</script>
